// 放置所有渲染进程发送的异步事件
import { app, ipcMain, shell } from 'electron'
import * as os from 'os'
import { readXls } from '../handle-xls'
import { exec } from 'child_process'
import path from 'path'
import fs from 'fs'
import { autoUpdater } from 'electron-updater'

ipcMain.handle('read-xls', (event, arg): xlsData => {
  console.log(event)
  const excelData = readXls(arg)
  return excelData
})

ipcMain.on('open-calc', () => {
  if (os.platform() === 'win32') {
    exec('calc.exe', (error) => {
      if (error) {
        console.error('打开win计算器失败', error)
      }
    })
  } else if (os.platform() === 'darwin') {
    exec('open -a Calculator', (error) => {
      if (error) {
        console.error('打开win计算器失败', error)
      }
    })
  }
  return
})

ipcMain.on('open-file', () => {
  const exePath = path.dirname(app.getPath('exe'))
  const folderPath = path.join(exePath, 'internalFile')
  if (fs.existsSync(folderPath)) {
    shell.openPath(folderPath)
  } else {
    fs.mkdirSync(folderPath)
    shell.openPath(folderPath)
  }
  return
})

ipcMain.on('close-app', () => {
  app.exit()
})

ipcMain.on('start-down', () => {
  autoUpdater.downloadUpdate()
})

ipcMain.on('check-update', () => {
  //检测更新
  autoUpdater.checkForUpdates()
})

ipcMain.on('install-update', () => {
  // 安装
  autoUpdater.quitAndInstall()
})
